package com.ellfors.common.app

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import com.alibaba.android.arouter.launcher.ARouter
import com.ellfors.common.BuildConfig
import com.ellfors.common.constant.RouterKey
import com.ellfors.common.ext.findProvider
import com.ellfors.common.utils.LogUtil
import com.orhanobut.logger.AndroidLogAdapter
import com.orhanobut.logger.DiskLogAdapter
import com.orhanobut.logger.Logger
import com.orhanobut.logger.PrettyFormatStrategy
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope


class MyApp : Application() {

    companion object {
        @SuppressLint("StaticFieldLeak")
        lateinit var context: Context

        val isDebug = BuildConfig.DEBUG

        val appScope: CoroutineScope = MainScope()
    }

    override fun onCreate() {
        super.onCreate()
        context = this

        initARouter()
        initHttpLogger()
        checkDeleteLogFile()

        initModuleApp()
    }

    init {
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout ->
            return@setDefaultRefreshHeaderCreator ClassicsHeader(context)
        }
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, layout ->
            ClassicsFooter.REFRESH_FOOTER_NOTHING = "没有更多数据了"
            return@setDefaultRefreshFooterCreator ClassicsFooter(context)
        }
        SmartRefreshLayout.setDefaultRefreshInitializer { context, layout ->

        }
    }

    private fun initModuleApp() {
        //这里其实只需要声明即可
        findProvider<AppLike>(RouterKey.MODULE_FIRST.APP)
    }

    private fun initARouter() {
        if (isDebug) {
            ARouter.openLog()
            ARouter.openDebug()
        }
        ARouter.init(this)
    }

    private fun initHttpLogger() {
        val formatStrategy =
            PrettyFormatStrategy
                .newBuilder()
                .showThreadInfo(false)
                .methodCount(0)
                .methodOffset(0)
                .tag("MyTest")
                .build()
        Logger.addLogAdapter(object : AndroidLogAdapter(formatStrategy) {
            override fun isLoggable(priority: Int, tag: String?): Boolean {
                return BuildConfig.DEBUG
            }
        })
        Logger.addLogAdapter(DiskLogAdapter())
    }

    private fun checkDeleteLogFile() {
        LogUtil.deleteLogFile()
    }
}